/*
 * @Description:对数据库的操作
 * @Author: YaoXiaotTian
 * @Date: 2021-04-18 15:24:57
 * @LastEditors: YaoXiaoTian
 * @LastEditTime: 2021-06-03 09:59:51
 */
const { query, queryAsync } = require("./mysql");
const db = require("./db");
const jwt = require("./jwt");
const { json } = require("express");
//获取用户信息（用户id需要从请求头中获取，需完善）
exports.getUserInfo = (req, res) => {
  let token = req.headers.authorization;
  checkToken(token).then((value) => {
    let { id } = jwt.verifyToken(token);
    let sql = `select * from user_information where userId =${id}`;
    query(sql, (err, result, fields) => {
      if (err) {
        res.json({
          code: -1,
          msg: err,
        });
        return;
      }
      let data = JSON.parse(JSON.stringify(result))[0];
      res.send({
        code: 0,
        data: data,
        msg: "获取用户信息成功",
      });
    });
  });
};

//编辑个人资料（用户id需要从请求头中获取，需完善）
exports.updateUserInfo = (req, res) => {
  let token = req.headers.authorization;
  checkToken(token).then((value) => {
    let { id } = jwt.verifyToken(token);
    let params = req.body;
    let key = Object.keys(params)[0];
    let sql = `update user_information set ${key} = ? where userId = ${id} `;
    query(sql, [params[key]], (err, result, fields) => {
      if (err) {
        res.json({
          code: -1,
          msg: err,
        });
        return;
      }
      res.json({
        code: 0,
        msg: "修改成功",
      });
    });
  });
};

//获取用户各种操作的数据
exports.getUserOptionalData = (req, res) => {
  let { userId } = req.query;
  let sql = `select * from user_optional where userId = ${userId}`;
  query(sql, (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: err,
      });
      return;
    }

    if (result.affectedRows === 1) {
      let temp = JSON.parse(JSON.stringify(result))[0];
      let favorites = temp.favorites.split(",").map((val) => {
        return Number.parseInt(val);
      });
      let attendtions = temp.attendtions.split(",").map((val) => {
        return Number.parseInt(val);
      });
      let fans = temp.fans.split(",").map((val) => {
        return Number.parseInt(val);
      });
      let thumbs = temp.thumbs.split(",").map((val) => {
        return Number.parseInt(val);
      });
      let like = temp.like.split(",").map((val) => {
        return Number.parseInt(val);
      });
      let dislike = temp.dislike.split(",").map((val) => {
        return Number.parseInt(val);
      });
      let report = temp.report.split(",").map((val) => {
        return Number.parseInt(val);
      });
      res.send({
        code: 0,
        data: {
          favorites,
          attendtions,
          fans,
          thumbs,
          like,
          dislike,
          report,
        },
        msg: "获取用户信息成功",
      });
    } else {
      res.json({
        code: 0,
        data: result,
        msg: "数据获取成功",
      });
    }
  });
};

//获取用户关注的人/粉丝数据
exports.getAttendtionsData = (req, res) => {
  let sql = `select nickName,fans,publish_num,introduction,avatar,userId from user_information where userId in (${req.query.userID})`;
  query(sql, (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: err,
      });
      return;
    }
    let data = JSON.parse(JSON.stringify(result));
    res.send({
      code: 0,
      data: data,
      msg: "获取用户信息成功",
    });
  });
};

//取消关注
exports.cancelAttendtion = (req, res) => {
  let userId = req.body.userId;
  let fansId = req.body.fansId;
  let sql1 = `update user_information set fans = fans - 1  where userId = ${userId}`;
  let sql = `update user_optional set fans=trim(both ',' from replace(concat(',',fans,','),'${
    "," + fansId + ","
  }',''))  where userId = ${userId}`;
  let sql3 = `update user_optional set attendtions=trim(both ',' from replace(concat(',',attendtions,','),'${
    "," + userId + ","
  }',''))  where userId = ${fansId}`;
  let sql2 = `insert into user_optional_record (type,userId,anotherUserId) values (?,?,?)`;
  let data = [13, fansId, userId];
  query(sql3, [], (err) => {
    if (err) {
      res.json({
        code: -1,
        msg: err,
      });
      return;
    }
    query(sql, [], (err, result, fields) => {
      if (err) {
        res.json({
          code: -1,
          msg: err,
        });
        return;
      }
      query(sql1, [], (err, result1, fields) => {
        if (err) {
          res.json({
            code: -1,
            msg: err,
          });
          return;
        }
        query(sql2, data, (err, result) => {
          if (err) {
            res.json({
              code: -1,
              msg: err,
            });
            return;
          }
          res.json({
            code: 0,
            msg: "取消关注成功",
          });
        });
      });
    });
  });
};

//关注
exports.attendtion = (req, res) => {
  let userId = req.body.userId;
  let fansId = req.body.fansId;
  let sql1 = `update user_information set fans = fans + 1  where userId = ${userId}`;
  let sql = `update user_optional set fans=concat(fans,',','${fansId}') where userId = ${userId}`;
  let sql3 = `update user_optional set attendtions=concat(attendtions,',','${userId}') where userId = ${fansId}`;
  let sql2 = `insert into user_optional_record (type,userId,anotherUserId) values (?,?,?)`;
  let data = [12, fansId, userId];
  query(sql, [], (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: err,
      });
      return;
    }
    query(sql3, (err, rusult3) => {
      if (err) {
        res.json({
          code: -1,
          msg: err,
        });
        return;
      }
      query(sql1, [], (err, result1, fields) => {
        if (err) {
          res.json({
            code: -1,
            msg: err,
          });
          return;
        }
        query(sql2, data, (err, result) => {
          if (err) {
            res.json({
              code: -1,
              msg: err,
            });
            return;
          }
          res.json({
            code: 0,
            msg: "恭喜你，关注成功",
          });
        });
      });
    });
  });
};
//首页图片话题
exports.getHomeImg = (req, res) => {
  let sql = "select id,img from article_data where type = 2 limit 5";
  query(sql, (err, result) => {
    if (err) {
      res.json({
        code: -1,
        msg: "数据获取失败",
      });
      return;
    }
    res.json({
      code: 0,
      data: result,
      msg: "数据获取成功",
    });
  });
};
//首页接口
exports.getHome = (req, res) => {
  let sql = "select id,title from article_data where type = 1 limit 10";
  let sql1 =
    "SELECT id,title,type,img,intro FROM entertainment_introduction ORDER BY RAND() LIMIT 10";
  let sql2 =
    "SELECT id,title,type,img,intro FROM entertainment_introduction a WHERE ( SELECT count(*) FROM entertainment_introduction b WHERE b.type = a.type AND b.id > a.id) < 5 ORDER BY type,id ";
  query(sql2, (err, result2, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: "首页数据获取失败，请稍后重试",
      });
      return;
    }
    query(sql, (err, result, fields) => {
      if (err) {
        res.json({
          code: -1,
          msg: "首页数据获取失败，请稍后重试",
        });
        return;
      }
      query(sql1, (err, result1, fields) => {
        if (err) {
          res.json({
            code: -1,
            msg: "首页数据获取失败，请稍后重试",
          });
          return;
        }
        let data1 = JSON.parse(JSON.stringify(result1));
        let data = JSON.parse(JSON.stringify(result));
        let data2 = JSON.parse(JSON.stringify(result2));
        res.json({
          code: 0,
          data: {
            hot_topic: data,
            hot_recommend: data1,
            latest_scenic_spot: data2.slice(0, 5),
            special_dishes: data2.slice(5, 10),
            latest_character: data2.slice(10),
          },
          msg: "数据获取成功",
        });
      });
    });
  });
};
// 获取所有的景区/人物/古迹
exports.getContent = (req, res) => {
  const { type, pageNo, pageSize } = req.query;
  let offset = (Number.parseInt(pageNo) - 1) * Number.parseInt(pageSize);
  let sql = `select id,title,img,type from entertainment_introduction where type = ${type} limit ${offset},${pageSize}`;
  let sql2 = `select count(1) as totalNum from entertainment_introduction where type = ${type}`;
  query(sql, (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: "数据获取失败，请稍后重试",
      });
      return;
    }
    query(sql2, (err, result1) => {
      if (err) {
        res.json({
          code: -1,
          msg: "数据获取失败，请稍后重试",
        });
        return;
      }
      let data = JSON.parse(JSON.stringify(result));
      res.json({
        code: 0,
        data: data,
        totalNum: JSON.parse(JSON.stringify(result1))[0].totalNum,
        msg: "数据获取成功",
      });
    });
  });
};
exports.getDetails = (req, res) => {
  const { id } = req.query;
  let sql = `select * from entertainment_introduction where id = ${id}`;
  query(sql, (err, result) => {
    if (err) {
      res.json({
        code: -1,
        msg: "数据获取失败，请稍后重试",
      });
      return;
    }
    res.json({
      code: 0,
      data: JSON.parse(JSON.stringify(result))[0],
      msg: "数据获取成功",
    });
  });
};
//用户注册
exports.addUser = (req, callback) => {
  let { phone, name, password, anotherPassword } = req.body;
  if (password !== anotherPassword) {
    callback.json({
      code: 1,
      message: "两次密码输入不一致",
    });
  }
  let get_user = "select * from user_information where account = ?";
  let get_data = [phone];
  db.base(get_user, get_data, (res) => {
    if (res.length) {
      callback.json({
        code: 1,
        message: "用户已存在",
      });
    }
    let set_user =
      "INSERT INTO user_information ( account,password, nickName ) VALUES (?,?,?);";
    let sql = `INSERT INTO user_optional(userId,attendtions,fans) (select userId,'0' as attendtions,'0' as fans from user_information where account = ${phone})`;
    let set_data = [phone, password, name];
    db.base(set_user, set_data, (res) => {
      if (res.affectedRows == 1) {
        db.base(sql, [], (res1) => {
          if (res1.affectedRows == 1) {
            callback.json({
              code: 0,
              message: "恭喜你注册成功，请您进行登录",
            });
          } else {
            callback.json({
              code: -1,
              message: "出了一点小问题，请稍后再试",
            });
          }
        });
      }
    });
  });
};
//获取时间
function getCurrentTime() {
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let strDate = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  if (hour >= 0 && hour <= 9) {
    hour = "0" + hour;
  }
  if (minute >= 0 && minute <= 9) {
    minute = "0" + minute;
  }
  let currentdate = `${year}-${month}-${strDate} ${hour}:${minute}`;
  return currentdate;
}
// 添加文章、视频、图片 post请求
exports.addArticle = (req, callback) => {
  let time = "";
  let { type, content, userId, title, intro, img, video } = req.body;
  let sql = "";
  time = getCurrentTime();
  let data = [];
  switch (type) {
    case 1:
      sql =
        "INSERT INTO article_data ( type,title, text, userId , intro,time ) VALUES (?,?,?,?,?,?);";
      data = [type, title, content, userId, intro, time];
      break;
    case 2:
      sql =
        "INSERT INTO article_data ( type,title, text, userId ,intro,img,time) VALUES (?,?,?,?,?,?,?);";
      data = [type, title, content, userId, intro, img, time];
      break;
    case 3:
      sql =
        "INSERT INTO article_data ( type,title, text, userId,intro,time,video) VALUES (?,?,?,?,?,?,?);";
      data = [type, title, content, userId, intro, time, video];
      break;
    default:
      break;
  }
  let sql2 = `update user_information set publish_num = publish_num + 1 where userId = ${userId}`;
  db.base(sql2, data, (res) => {
    if (res.affectedRows == 1) {
      db.base(sql, data, (res) => {
        if (res.affectedRows == 1) {
          callback.json({
            code: 0,
            msg: "新增成功",
          });
        } else {
          callback.json({
            code: "-1",
            msg: "好像出了一点问题，请稍后重试",
          });
        }
      });
    } else {
      callback.json({
        code: "-1",
        msg: "好像出了一点问题，请稍后重试",
      });
    }
  });
};
// 添加评论
exports.addComment = (req, callback) => {
  let {
    parentId,
    articleId,
    userId,
    reply_userId,
    content,
    reply_nickName,
    reply_avatar,
  } = req.body;
  let sql = "";
  let data = [];
  let sql1 = `insert into user_optional_record (type,userId,reviewId,reviewContent) values (?,?,?,?)`;
  let data1 = [4, userId, 0, content];
  if (parentId) {
    sql =
      "INSERT INTO comment_data ( parentId,articleId, userId, reply_userId, content, reply_nickName,reply_avatar ) VALUES (?,?,?,?,?,?,?);";
    data = [
      parentId,
      articleId,
      userId,
      reply_userId,
      content,
      reply_nickName,
      reply_avatar,
    ];
  } else {
    sql =
      "INSERT INTO comment_data ( articleId, userId, content ) VALUES (?,?,?);";
    data = [articleId, userId, content];
  }
  db.base(sql, data, (res) => {
    if (res.affectedRows == 1) {
      query(sql1, data1, (err, result) => {
        if (err) {
          callback.json({
            code: -1,
            msg: "出了一点问题，请稍后重试",
          });
          return;
        }
      });
      callback.json({
        code: 0,
        msg: "新增成功",
      });
    } else {
      callback.json({
        code: -1,
        msg: "发表失败",
      });
    }
  });
};
// 删除评论
exports.deleteComment = (req, res) => {
  let { id, userId, content } = req.query;
  let sql = `update comment_data set content = '用户已删除该条评论' where id = ${id}`;
  let sql1 = `insert into user_optional_record (type,userId,reviewId,reviewContent) values (?,?,?,?)`;
  let data = [4, userId, id, content];
  query(sql, [], (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        // msg: err,
        msg: "评论删除失败",
      });
      return;
    }
    query(sql1, data, (err, result) => {
      if (err) {
        res.json({
          code: -1,
          // msg: err,
          msg: "评论删除失败",
        });
        return;
      }
      res.json({
        code: 0,
        msg: "评论删除成功",
      });
    });

    return;
  });
};
//获取评论
exports.getComment = (req, res) => {
  let { articleId } = req.query;
  let sql = "CALL showTreeNodes_yongyupost2000 (0);";
  let result = [];
  let sql1 = `SELECT A.*, B.nLevel,C.nickName,C.avatar FROM comment_data A,tmpLst B,user_information C WHERE A.id = B.id AND A.userId = C.userId AND A.articleId = ${articleId} ORDER BY B.sCort;`;
  query(sql, (err, result2, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: err,
      });
      return;
    }
    query(sql1, (err, result1, fields) => {
      if (err) {
        res.json({
          code: -1,
          msg: err,
        });
        return;
      }
      result = JSON.parse(JSON.stringify(result1));
      let data = [];
      let index = -1;
      result.forEach((element) => {
        if (element.nLevel == 0) {
          index++;
          element["children"] = [];
          data.push(element);
        } else {
          data[index]["children"].push(element);
        }
      });
      res.json({
        code: 0,
        data: data,
        totalNum: result.length,
        msg: "操作成功",
      });
    });
  });
};

// 登录 post请求
exports.apiLogin = (req, callback) => {
  let { phone, password, source } = req.body;
  let sql;
  if (Number.parseInt(source) === 2) {
    sql =
      "select * from user_information where account = ? and password = ? and type = 2";
  } else {
    sql = "select * from user_information where account = ? and password = ?";
  }

  let data = [phone, password];
  db.base(sql, data, (res) => {
    if (res.length == 1) {
      let _data = res[0];
      let id = res[0].userId;
      let token = jwt.generateToken(id);
      _data.token = token;
      upToken(token, id);
      callback.json({
        code: 0,
        data: _data,
        message: "登录成功",
      });
    } else {
      callback.json({
        code: 1,
        message: "账号或密码错误",
      });
    }
  });
};

// 退出登录
exports.apiLoginOut = (req, res) => {
  let json = req;
  console.log(json);
  let token = json.headers.authorization
    ? json.headers.authorization
    : json.body.token;
  console.log(token);
  checkToken(token).then((value) => {
    let { id } = jwt.verifyToken(token);
    let sql = "UPDATE user_information SET token=0 where userId=?";
    let data = [id];
    db.base(sql, data, (results) => {
      if (results.affectedRows > 0) {
        res.json({
          code: 0,
          msg: "退出成功",
        });
      } else {
        res.json({
          code: -1,
          msg: "网络错误",
        });
      }
    });
  });
};

// 更新token
function upToken(token, id) {
  let sql = "UPDATE user_information SET token=? where userId=?";
  let data = [token, id];
  db.base(sql, data, (results) => {
    console.log(results);
  });
}
// 判断token是否相等
function checkToken(token) {
  return new Promise((resolve, reject) => {
    let bdtoken = token;
    let { id } = jwt.verifyToken(bdtoken);
    let sql = "SELECT token FROM user_information where userId=?";
    let data = [id];
    db.base(sql, data, (results) => {
      if (bdtoken == results[0].token) {
        resolve(true);
      } else {
        reject(false);
      }
    });
  });
}

// 发送私信
exports.sendPrivateLetter = (req, res) => {
  let { postUserId, getUserId, type, content } = req.body;
  let sql =
    "INSERT INTO private_letter ( postUserId, getUserId,type,content ) VALUES(?,?,?,?);";
  query(sql, [postUserId, getUserId, type, content], (err, result, fields) => {
    if (err) {
      console.log(err);
      res.json({
        code: -1,
        msg: "私信发送失败",
      });
      return;
    }
    res.json({
      code: 0,
      msg: "私信发送成功",
    });
  });
};

//文章的各种操作
// type 1 -->点赞，4-->收藏,5-->喜欢,6-->举报,7-->不感兴趣,
//operate true:正向操作 false反向操作
exports.operateRecord = (req, res) => {
  let { type, articleId, userId, operate, ...params } = req.body;
  let sql = "";
  let sql1 = "";
  let column = "";
  let type2 = 0; //用户操作的类型，用于用户操作记录表中
  switch (Number.parseInt(type)) {
    case 1:
      column = "thumbs";
      if (operate) {
        type2 = 1;
      } else {
        type2 = 2;
      }
      break;
    case 4:
      column = "favorites";
      if (operate) {
        type2 = 5;
      } else {
        type2 = 6;
      }
      break;
    case 5:
      column = "like";
      if (operate) {
        type2 = 7;
      } else {
        type2 = 8;
      }
      break;
    case 6:
      column = "report";
      type2 = 9;
      break;
    case 7:
      column = "dislike";
      type2 = 11;
      break;
  }
  if (operate) {
    // 点赞，收藏，喜欢,举报，不喜欢
    sql = `update user_optional set ${column}=concat(${column},',','${articleId}') where userId = ${userId}`;
  } else {
    // 取消点赞，取消收藏，取消喜欢
    sql = `update user_optional set ${column}=trim(both ',' from replace(concat(',',${column},','),'${
      "," + articleId + ","
    }',''))  where userId = ${userId}`;
  }
  query(sql, [], (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: "好像出了一点问题哦，请稍后再试",
      });
      return;
    }
    let sql2 = `insert into user_optional_record (type,articleId,userId) values (?,?,?)`;
    let data = [type2, articleId, userId];
    if (type == "1" || type == 1) {
      if (operate) {
        sql1 = `update article_data set thumbs = thumbs + 1  where id = ${articleId}`;
      } else {
        sql1 = `update article_data set thumbs = thumbs - 1  where id = ${articleId}`;
      }
      query(sql1, [], (err, result1, fields) => {
        if (err) {
          res.json({
            code: -1,
            msg: "好像出了一点问题，请稍后再试",
          });
          return;
        }
        query(sql2, data, (err, result3, fields) => {
          if (err) {
            res.json({
              code: -1,
              msg: "好像出了一点问题，请稍后再试",
            });
            return;
          }
        });
      });
    } else if (type == "6" || type == 6) {
      let sql1 =
        "insert into report_news (userId,articleId,nickName,articleTitle,reason) values (?,?,?,?,?)";
      query(
        sql1,
        [
          userId,
          articleId,
          params.nickName,
          params.articleTitle,
          params.reason,
        ],
        (err, result1, fields) => {
          if (err) {
            res.json({
              code: -1,
              msg: "好像出了一点问题，请稍后再试",
            });
            return;
          }
          query(sql2, data, (err, result3, fields) => {
            if (err) {
              res.json({
                code: -1,
                msg: "好像出了一点问题，请稍后再试",
              });
              return;
            }
          });
        }
      );
    } else {
      query(sql2, data, (err, result3, fields) => {
        if (err) {
          res.json({
            code: -1,
            msg: "好像出了一点问题，请稍后再试",
          });
          return;
        }
      });
    }
    res.json({
      code: 0,
      msg: "操作成功",
    });
  });
};

//获取系统通知/私信/评论（回复）接口 (type 3 -->系统通知，1-->私信,2-->评论(回复))
// isOnlyNum true-->只需要总数不需要内容
exports.getNews = (req, res) => {
  let { userId, type, isOnlyNum } = req.query;
  let sql = "";
  if (isOnlyNum == "true") {
    if (type == "3") {
      sql = `select count(1) as totalNum from system_info where userId = ${userId} and isRead = 0`;
    } else {
      sql = `select count(1) as totalNum from private_letter where getUserId = ${userId} and isRead = 0`;
    }
  } else {
    if (type == "3") {
      sql = `select * from system_info where userId = ${userId} order by isRead asc,time desc`;
    } else {
      sql = `select A.*,B.avatar from private_letter A,user_information B where A.getUserId = ${userId} and A.type = ${type} and A.postUserId = B.userId order by isRead asc,time desc`;
    }
  }
  query(sql, (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg:
          type == "3"
            ? "获取系统消息失败，请稍后重试"
            : type == "1"
            ? "获取私信消息失败，请稍后重试"
            : "获取评论/回复消息失败，请稍后重试",
        // msg: err,
      });
      return;
    }
    result = JSON.parse(JSON.stringify(result));
    if (isOnlyNum == "true") {
      res.json({
        code: 0,
        totalNum: result[0].totalNum,
        msg: "操作成功",
      });
    } else {
      res.json({
        code: 0,
        data: result,
        msg: "操作成功",
      });
    }
  });
};
//更新消息的状态
exports.updateNews = (req, res) => {
  let { userId, type } = req.query;
  let sql = "";
  if (type == "3") {
    sql = `update system_info set isRead = 1 where id in (select A.id from (select id from system_info where userId = ${userId} and isRead = 0) A)`;
  } else {
    sql = `update private_letter set isRead = 1 where id in (select A.id from (select id from private_letter where getUserId = ${userId} and type = ${type} and isRead = 0) A)`;
  }
  query(sql, (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg:
          type == "3"
            ? "更新系统消息已读状态失败，请稍后重试"
            : type == "1"
            ? "更新私信消息已读状态失败，请稍后重试"
            : "更新评论/回复消息已读状态失败，请稍后重试",
        // msg: err,
      });
      return;
    }
    result = JSON.parse(JSON.stringify(result));
    res.json({
      code: 0,
      data: result,
      msg: "操作成功",
    });
  });
};

// 获取互动版块内容 type 1-->全部，2-->关注，3-->热榜
exports.getArticleData = (req, res) => {
  let { type, userId } = req.query;
  let sql = "";
  switch (type) {
    case "1":
      sql =
        // "";
        "select id,title,img,intro,thumbs from article_data order by time desc";
      break;
    case "2":
      sql = `select id,title,img,intro,thumbs from article_data where userId in (select attendtions from user_optional where userId = ${userId})`;
      break;
    case "3":
      sql =
        "select id,title,img,intro,thumbs from article_data order by thumbs desc";
      break;
    default:
      break;
  }
  query(sql, (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: "好像出了一点问题哦，请稍后再试",
        // msg: err,
      });
      return;
    }
    result = JSON.parse(JSON.stringify(result));
    res.json({
      code: 0,
      data: result,
      totalNum: result.length,
      msg: "操作成功",
    });
  });
};
// 获取文章的数据详细数据
exports.getArticle = (req, res) => {
  let { articleId } = req.query;
  let sql = `select A.*,B.nickName,B.introduction,B.avatar from article_data as A,user_information as B where A.userId = B.userId and A.id = ${articleId}`;
  query(sql, (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: "好像出了一点问题哦，请稍后再试",
        // msg: err,
      });
      return;
    }
    result = JSON.parse(JSON.stringify(result));
    res.json({
      code: 0,
      data: result[0],
      msg: "操作成功",
    });
  });
};
// 获取文章模糊查询内容
exports.getSearchData = (req, res) => {
  let { searchStr } = req.query;
  searchStr = "%" + searchStr + "%";
  let sql = `select id,title,img,intro,thumbs from article_data where title like '${searchStr}'`;
  query(sql, (err, result, fields) => {
    if (err) {
      res.json({
        code: -1,
        msg: "好像出了一点问题哦，请稍后再试",
        // msg: err,
      });
      return;
    }
    result = JSON.parse(JSON.stringify(result));
    res.json({
      code: 0,
      data: result,
      totalNum: result.length,
      msg: "操作成功",
    });
  });
};
// 获取个人中心的文章数据
exports.getPersonArticleData = async (req, res) => {
  let { type, userId } = req.query;
  let sql = "";
  let data = [];
  let result = [];
  if (type != "0") {
    let sql1 = "";
    if (type == "4") {
      sql1 = `select favorites from user_optional where userId = ${userId}`;
      let result1 = await queryAsync(sql1);
      if (result1[1]) {
        sql = `select * from article_data where id in (${result1[1][0].favorites}) order by time desc`;
      } else {
        res.json({
          code: -1,
          msg: result[0],
        });
        return;
      }
    } else {
      sql = `select * from article_data where userId = ${userId} and type = ${type} order by time desc`;
    }
    query(sql, (err, result, fields) => {
      if (err) {
        res.json({
          code: -1,
          msg: "好像出了一点问题哦，请稍后再试",
          // msg: err,
        });
        return;
      }
      result = JSON.parse(JSON.stringify(result));
      res.json({
        code: 0,
        data: result,
        totalNum: result.length,
        msg: "操作成功",
      });
    });
  } else {
    sql = `select A.*,B.img,B.title,B.intro,B.thumbs,B.userId as writerId from user_optional_record as A,article_data as B where A.userId = ${userId} and A.articleId is not null and A.articleId = B.id`;
    result = await queryAsync(sql);
    if (result[1]) {
      data = result[1];
    } else {
      res.json({
        code: -1,
        msg: result[0],
      });
      return;
    }
    sql = `select A.*,B.nickName,B.avatar,B.introduction from user_optional_record A,user_information B where A.userId = ${userId} and A.anotherUserId is not null and A.anotherUserId = B.userId`;
    result = await queryAsync(sql);
    if (result[1].length) {
      data = [...data, ...result[1]];
    } else {
      data = [];
      res.json({
        code: -1,
        msg: result[0],
      });
      return;
    }
    sql = `select * from user_optional_record A where A.userId = ${userId} and A.reviewId is not null`;
    result = await queryAsync(sql);
    if (result[1]) {
      data = [...data, ...result[1]];
    } else {
      data = [];
      res.json({
        code: -1,
        msg: result[0],
      });
      return;
    }
  }
  if (type == "0") {
    if (data.length) {
      data = data.sort(compare("id"));
      res.json({
        code: 0,
        data: data,
        totalNum: data.length,
        msg: "操作成功",
      });
    } else {
      res.json({
        code: 1,
        msg: "暂时还没有数据",
      });
    }
  }
};
// 排序
function compare(property) {
  return (a, b) => {
    return a[property] - b[property];
  };
}
